/**
  ******************************************************************************
  * @file    WF_GetRadioMAC.c
  * @author  exatron
  * @version V1.0.0
  * @date    segunda, 22 de dezembro de 2014
  * @brief   Devolve pela serial o endereço MAC da wlan0.
  ******************************************************************************
  * @attention
  *
  *
  ******************************************************************************
  */

/** @addtogroup WF
  * @{
  */

/* Includes ------------------------------------------------------------------*/
#include <common.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <unistd.h>

/* External functions --------------------------------------------------------*/

/** @defgroup WF_Functions
  * @{
  */

/**
  * @brief  Devolve pela serial o endereço MAC da wlan0.
  * @param  Nenhum
  * @retval Devolve pela serial o MAC ou Result_t
  */
void WF_GetRadioMAC()
{
    int dSocket;                    /*!< Socket para manipulação de ioctl */
    struct ifreq xIRS;              /*!< Interface request structure */
    #ifdef DEBUG_ON_PC
    char *iface = "eth0";           /*!< Nome da interface */
    #else
    char *iface = "wlan0";          /*!< Nome da interface */
    #endif
    unsigned char *mac = NULL;      /*!< Buffer */

    /* Zera a estrutura xIRS */
    memset(&xIRS, 0, sizeof(struct ifreq));

    /* Cria socket, família AF_INET, tipo sequencial */
    dSocket = socket(AF_INET, SOCK_STREAM, 0);
    if(dSocket != -1) // Socket Ok
    {
       	/* Informa a família ao xIRS */
        xIRS.ifr_addr.sa_family = AF_INET;

        /* Copia nome da interface para a estrutura xIRS */
        strcpy(xIRS.ifr_name, iface);

        /* Faz a requisição do comando SIOCGIFHWADDR ao I/O
         * dSocket
         */
        if(ioctl(dSocket, SIOCGIFHWADDR, &xIRS) != -1) // ioctl Ok
        {
            mac = (unsigned char *)xIRS.ifr_hwaddr.sa_data;
            aux_USART0_puts("%s=%d;%02X:%02X:%02X:%02X:%02X:%02X\r\n", "WF_GRM", Result_Ok, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
        }
        else // ioctl error
        {
            aux_USART0_puts("%s=%d\r\n", "WF_GRM", Result_IoctlError);
        }
        close(dSocket);
    }
    else // Socket error
    {
        aux_USART0_puts("%s=%d\r\n", "WF_GRM", Result_OnOpen);
    }

    aux_SetBusy(FALSE);
}

/**
  * @}
  */

/**
  * @}
  */
